package com.leetcode.根据数据结构分类.数组;

/**
 * @author: ZhouBert
 * @date: 2021/2/25
 * @description: 867. 转置矩阵
 * https://leetcode-cn.com/problems/transpose-matrix/
 */
public class A_867_转置矩阵 {


	public static void main(String[] args) {

	}


	/**
	 * 直接交换即可，顺便考虑一下 m!=n 的情况
	 * 好像是我考虑太多了...
	 * @param matrix
	 * @return
	 */
	public int[][] transpose(int[][] matrix) {
		int m = matrix.length;
		int n = matrix[0].length;
		int min = Math.min(m, n);
		int[][] flipArr = new int[n][m];
		for (int i = 0; i < min; i++) {
			flipArr[i][i] = matrix[i][i];
			for (int j = i + 1; j < min; j++) {
				//只交换对角线上半部分
				flip(matrix, i, j, flipArr);
			}
		}
		//
		if (m > n) {
			//如果行数大于列数
			for (int i = min; i < m; i++) {
				for (int j = 0; j < n; j++) {
					set(matrix, i, j, flipArr);
				}
			}
		} else if (m < n) {
			for (int i = 0; i < m; i++) {
				for (int j = min; j < n; j++) {
					set(matrix, i, j, flipArr);
				}
			}
		}

		return flipArr;
	}

	private void set(int[][] matrix, int i, int j, int[][] flipArr) {
		flipArr[j][i] = matrix[i][j];
	}

	/**
	 * @param matrix
	 * @param i
	 * @param j
	 * @param flipArr
	 */
	private void flip(int[][] matrix, int i, int j, int[][] flipArr) {
		flipArr[i][j] = matrix[j][i];
		flipArr[j][i] = matrix[i][j];
	}


	private void swap(int[][] matrix, int i, int j) {
		int temp = matrix[i][j];
		matrix[i][j] = matrix[j][i];
		matrix[j][i] = temp;
	}
}
